package worklog.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import worklog.db.ProjectChartDB;
import worklog.dto.ProjectChartDTO;
import worklog.dto.ResponseDTO;

@WebServlet("/mostActiveProjects")
public class MostActiveProjects extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ProjectChartDB projectDB;
	private ResponseDTO responder = new ResponseDTO();
	
    public MostActiveProjects () throws Exception{ 
    	super();
    }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		//doGet(request, response); 
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		projectDB = new ProjectChartDB();
		PrintWriter out = response.getWriter();
		response.setContentType("application/json");
    	if (projectDB.isReady()) out.print(processRequest(request));
    	else out.print(responder.showError("DB connection error"));
    	projectDB.close();
    	out.close();
	}
	
	private String processRequest(HttpServletRequest request){
		ArrayList<ProjectChartDTO> projectsArray = new ArrayList<ProjectChartDTO>();
    	try {
    		projectsArray = projectDB.mostActive();
		} 
    	catch (SQLException e) {}
    	
    	if (projectsArray != null) return projectsArray.toString();
    	else return "{}";
	}	
}